<template>
  <div class="wechat-login">
    <button :disabled="loading"
@click="handleWechatLogin">
      <img
src="@/assets/wechat-logo.png" alt="微信登录" />
      <span v-if="!loading">微信一键登录</span>
      <span v-else>授权中...</span>
    </button>
    <div v-if="error"
class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'

  const router = useRouter()
  const loading = ref(false)
  const error = ref('')

  const handleWechatLogin = async () => {
    try {
      loading.value = true
      error.value = ''

      // 1. 检查是否在微信环境
      if (!isWeixinBrowser()) {
        error.value = '请在微信中打开进行授权登录'
        return
      }

      // 2. 初始化微信配置
      await initWechatConfig()

      // 3. 执行微信授权
      const authResult = await wechatAuth()

      // 4. 处理授权结果
      if (authResult.success) {
        // 绑定或登录逻辑
        await handleAuthSuccess(authResult.data)
        router.push('/')
      } else {
        error.value = authResult.message || '授权失败'
      }
    } catch (err) {
      error.value = '授权过程出错，请重试'
      console.error('微信登录错误:', err)
    } finally {
      loading.value = false
    }
  }

  // 检查微信环境
  const isWeixinBrowser = () => {
    const ua = navigator.userAgent.toLowerCase()
    return ua.includes('micromessenger')
  }

  // 初始化微信配置
  const initWechatConfig = async () => {
    try {
      await initWechatSDK()
      return true
    } catch (error) {
      error.value = '微信SDK初始化失败'
      return false
    }
  }

  // 微信授权
  const wechatAuth = async () => {
    try {
      // 先尝试静默授权获取基本信息
      const basicInfo = await wechatAuthLogin('snsapi_base')

      // 如果已有绑定关系，直接登录
      if (basicInfo.isBound) {
        return {
          success: true,
          data: basicInfo.user,
        }
      }

      // 否则进行完整授权获取用户信息
      const fullInfo = await wechatAuthLogin('snsapi_userinfo')
      return {
        success: true,
        data: fullInfo,
        needBind: !fullInfo.isBound,
      }
    } catch (error) {
      return {
        success: false,
        message: error.message,
      }
    }
  }

  // 处理授权成功
  const handleAuthSuccess = async authResult => {
    if (authResult.needBind) {
      // 显示绑定界面
      router.push({
        path: '/bind-account',
        query: {
          openid: authResult.data.openid,
          nickname: authResult.data.nickname,
          avatar: authResult.data.avatar,
        },
      })
    } else {
      // 直接登录成功
      router.push('/')
    }
  }
</script>

<style scoped>
  .wechat-login {
    margin-top: 20px;
    text-align: center;
  }

  .wechat-login button {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: #07c160;
    color: white;
    border: none;
    padding: 10px 15px;
    border-radius: 5px;
    width: 100%;
  }

  .wechat-login button:disabled {
    opacity: 0.7;
  }

  .wechat-login img {
    width: 20px;
    height: 20px;
  }

  .error-message {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 8px;
  }
</style>
